from pathlib import Path
from datetime import timedelta
import os
from dotenv import load_dotenv
from ctbloge.scripts.logging import config_logging, config_debug_logging
from ctbloge.scripts.rest_framework import config_rest_framework
from ctbloge.scripts.config_menu import config_menu
from ctbloge.scripts.config_cors import config_cors, config_debug_cors

BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / '.env')

# 安全配置
SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-fallback-key')
DEBUG = os.environ.get('DEBUG', 'True') == 'True'

# 应用配置
INSTALLED_APPS = [
    'simpleui',  # simpleui美化后台
    'crispy_forms',  # crispy表单美化
    'corsheaders',  # 跨域请求头
    'ctbloge.apps.accounts',  # 用户管理应用-自定义用户模型
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',  # restful框架
    'drf_spectacular',  # drf文档自动生成
    'drf_spectacular_sidecar',  # drf文档自动生成
    'mptt',  # mptt树形结构应用,评论应用依赖
    'django_ckeditor_5',

    'django_apscheduler',

    'ctbloge.apps.blog',  # 博客应用-站点管理、文章管理、分类管理、标签管理
    'ctbloge.apps.cms',  # 内容管理系统应用
    'ctbloge.apps.comments',  # 评论应用
    'ctbloge.apps.resources',  # 资源管理应用
    'ctbloge.apps.schedulers',  # 定时任务应用

]
# 定时任务配置
APSCHEDULER_TIMEZONE = 'Asia/Shanghai'  # 时区
APSCHEDULER_DATETIME_FORMAT = "N j, Y, f:s a"  # 时间格式
APSCHEDULER_RUN_NOW_TIMEOUT = 25  # 允许立即运行的最大超时
ENABLE_SCHEDULER = True  # 是否开启定时任务

# 用户模型配置
AUTH_USER_MODEL = 'accounts.UserProfile'
# 富文本编辑器配置,默认使用ckeditor5

# CKEditor 5的配置
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                    'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],
    },
    'extends': {
        'blockToolbar': [
            'paragraph', 'heading1', 'heading2', 'heading3',
            '|',
            'bulletedList', 'numberedList',
            '|',
            'blockQuote',
        ],
        'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough',
                    'code', 'subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage',
                    'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|',
                    'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat',
                    'insertTable', ],
        'image': {
            'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft',
                        'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'],
            'styles': [
                'full',
                'side',
                'alignLeft',
                'alignRight',
                'alignCenter',
            ]
        },
        'language': 'zh-cn',
        'placeholder': '请在此处输入内容...',
        'codeBlock': {
            'languages': [
                {'label': 'HTML/XML', 'language': 'xml'},
                {'label': 'JavaScript', 'language': 'javascript'},
                {'label': 'CSS', 'language': 'css'},
                {'label': 'Python', 'language': 'python'},
                {'label': 'Java', 'language': 'java'},
                {'label': 'PHP', 'language': 'php'},
                {'label': 'Ruby', 'language': 'ruby'},
                {'label': 'SQL', 'language': 'sql'},
                {'label': 'C++', 'language': 'cpp'},
                {'label': 'C#', 'language': 'csharp'},
                {'label': 'Go', 'language': 'go'},
                {'label': 'Swift', 'language': 'swift'},
                {'label': 'TypeScript', 'language': 'typescript'},
                {'label': 'JSON', 'language': 'json'},
                {'label': 'Markdown', 'language': 'markdown'},
                {'label': 'YAML', 'language': 'yaml'},
            ],
        },
        'heading': {
            'options': [
                {'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph'},
                {'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1'},
                {'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2'},
                {'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3'},
                {'model': 'heading4', 'view': 'h4', 'title': 'Heading 4', 'class': 'ck-heading_heading4'},
                {'model': 'heading5', 'view': 'h5', 'title': 'Heading 5', 'class': 'ck-heading_heading5'},
            ]
        }
    },
    'list': {
        'properties': {
            'styles': 'true',
            'startIndex': 'true',
            'reversed': 'true',
        }
    }
}

# DRF配置
REST_FRAMEWORK = config_rest_framework()

# JWT配置
SIMPLE_JWT = {
    'AUTH_HEADER_TYPES': ('Bearer',),
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=int(os.environ.get('JWT_ACCESS_LIFETIME', '1440'))),  # 1天
    'REFRESH_TOKEN_LIFETIME': timedelta(minutes=int(os.environ.get('JWT_REFRESH_LIFETIME', '10080')))  # 7天
}

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CSRF_TRUSTED_ORIGINS = ['http://localhost:5173', 'http://127.0.0.1:5173']

if DEBUG:  # 开发环境
    LOGGING = config_debug_logging()  # 调试模式日志配置
    ALLOWED_HOSTS = ['*']
    # 跨域配置
    CORS_ALLOW_ALL_ORIGINS = config_debug_cors()['CORS_ALLOW_ALL_ORIGINS']
    CORS_ALLOW_CREDENTIALS = config_debug_cors()['CORS_ALLOW_CREDENTIALS']
    CORS_ALLOWED_ORIGINS = config_debug_cors()['CORS_ALLOWED_ORIGINS']
    # 数据库配置
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ.get('MYSQL_DATABASE', 'ctbloge'),
            'USER': 'root',
            'PASSWORD': '123456',
            'HOST': 'localhost',
            'PORT': '3306',
            'OPTIONS': {
                'charset': 'utf8mb4',
            }
        }
    }
    # 缓存配置（使用环境变量）
    CACHES = {
        'default': {
            'BACKEND': os.environ.get('CACHE_BACKEND', 'django_redis.cache.RedisCache'),
            'LOCATION': 'redis://localhost:6379/0',
            'TIMEOUT': '300',
            'OPTIONS': {
                'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            }
        }
    }
else:  # 生产环境
    LOGGING = config_logging(BASE_DIR)  # 生产模式日志配置
    ALLOWED_HOSTS = ['localhost', '127.0.0.1', os.environ.get('HOST_URL', '')]
    CORS_ALLOW_ALL_ORIGINS = config_cors(os.environ.get('HOST_URL', ''))['CORS_ALLOW_ALL_ORIGINS']
    CORS_ALLOW_CREDENTIALS = config_cors(os.environ.get('HOST_URL', ''))['CORS_ALLOW_CREDENTIALS']
    CORS_ALLOWED_ORIGINS = config_cors(os.environ.get('HOST_URL', ''))['CORS_ALLOWED_ORIGINS']
    # 数据库配置
    DATABASES = {
        'default': {
            'ENGINE': os.environ.get('MYSQL_ENGINE'),
            'NAME': os.environ.get('MYSQL_DATABASE'),
            'USER': os.environ.get('MYSQL_USER'),
            'PASSWORD': os.environ.get('MYSQL_PASSWORD'),
            'HOST': os.environ.get('MYSQL_HOST'),
            'PORT': os.environ.get('MYSQL_PORT'),
            'OPTIONS': {
                'charset': 'utf8mb4',
            }
        }
    }
    mysql_root_password = os.environ.get('MYSQL_ROOT_PASSWORD', 'root')
    # 缓存配置（使用环境变量）
    CACHES = {
        'default': {
            'BACKEND': os.environ.get('CACHE_BACKEND', 'django_redis.cache.RedisCache'),
            'LOCATION': 'redis://{}:{}/{}'.format(os.environ.get('REDIS_HOST'),
                                                  os.environ.get('REDIS_PORT'),
                                                  os.environ.get('REDIS_DB')),
            'TIMEOUT': int(os.environ.get('CACHE_TIMEOUT')),
            'OPTIONS': {
                'CLIENT_CLASS': os.environ.get('CACHE_CLIENT_CLASS'),
            }
        }
    }

ROOT_URLCONF = 'ctbloge.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ctbloge.wsgi.application'

# 邮箱配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.environ.get('EMAIL_HOST', 'smtp.qq.com')
EMAIL_PORT = int(os.environ.get('EMAIL_PORT', '587'))
EMAIL_USE_SSL = os.environ.get('EMAIL_USE_SSL', 'True') == 'True'
EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS', 'False') == 'True'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')

# 密码验证配置
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# 时区配置
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False

# 静态文件配置（Vite前端构建输出路径）
STATIC_URL = '/static/'  # 静态文件url
STATIC_ROOT = Path(BASE_DIR, 'ctbloge/staticfiles')  # 静态文件输出目录
# STATICFILES_DIRS = [Path(BASE_DIR, 'ctbloge/staticfiles/build')]
# WEBPACK_MANIFEST_FILE = Path(BASE_DIR, 'frontend/build/manifest.json')

# 媒体文件配置（上传文件路径）
MEDIA_URL = '/media/'
MEDIA_ROOT = Path(BASE_DIR, 'ctbloge/uploads')

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# simpleui配置
SIMPLEUI_THEME = 'layui'  # 强制使用Layui主题
# simpleui菜单配置
SIMPLEUI_DEFAULT_ICON = 'fa fa-file-text'  # 菜单默认图标
SIMPLEUI_ANALYSIS = False  # 关闭使用统计
SIMPLEUI_HOME_INFO = False  # 关闭首页信息
SIMPLEUI_HOME_PAGE = '/api/blog/dashboard/'
SIMPLEUI_HOME_TITLE = '仪表盘'  # 首页标题
SIMPLEUI_HOME_ICON = 'fa fa-dashboard'  # 首页图标
# 设置右上角Home图标跳转链接，会以另外一个窗口打开
SIMPLEUI_INDEX = 'https://{}'.format(os.environ.get('HOST_URL', 'www.ctbloge.top'))
# 登录页配置
SIMPLEUI_LOGIN_PARTICLES = True  # 开启登录页粒子动画
SIMPLEUI_LOGIN_FIELD_REQUIRED = True  # 登录页必填项提示
# 自定义菜单配置
SIMPLEUI_CONFIG = config_menu()

# crispy_forms配置
CRISPY_TEMPLATE_PACK = 'bootstrap4'  # 使用bootstrap4模板

# #swagger配置
# SWAGGER_SETTINGS = {
#     'SECURITY_DEFINITIONS': {
#         'Bearer': {
#             'type': 'apiKey',
#             'name': 'Authorization',
#             'in': 'header'
#         }
#     },
#     'USE_SESSION_AUTH': True,
#     'JSON_EDITOR': True,
#     'DEEP_LINKING': True,
#     'DEFAULT_MODEL_RENDERING': "example",
#     'DEFAULT_FIELD_INSPECTORS': [
#         'drf_yasg.inspectors.CamelCaseJSONFilter',
#         'drf_yasg.inspectors.InlineSerializerMethodInspector'
#     ],
# }

REDOC_SETTINGS = {
    'LAZY_RENDERING': False,
    'SPEC_URL': ('schema-json', {'format': '.json'}),
}
# Spectacular配置
SPECTACULAR_SETTINGS = {
    'TITLE': '川塔博客CMS API',
    'DESCRIPTION': '川塔博客内容管理系统接口文档',
    'VERSION': '1.0.0',
    # 'SERVE_INCLUDE_SCHEMA': False,
    # 'SCHEMA_PATH_PREFIX':None,
    'SWAGGER_UI_DIST': 'SIDECAR',
    'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
    'SWAGGER_UI_SETTINGS': {
        'deepLinking': True,
        'persistAuthorization': True,
        'displayOperationId': True,
    },
    # 'REDOC_DIST': 'SIDECAR',
    'COMPONENT_SPLIT_REQUEST': True,
    'SCHEMA_COERCE_PATH_PK_SUFFIX': True,
}

# 文件上传限制
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024  # 10MB
FILE_UPLOAD_MAX_MEMORY_SIZE = 20 * 1024 * 1024  # 20MB

# 允许的图片类型
ALLOWED_IMAGE_TYPES = [
    'image/jpeg',
    'image/png',
    'image/webp',
    'image/gif'
]

# 第三方登录各平台配置
QQ_CLIENT_ID = os.environ.get('QQ_CLIENT_ID', '')
QQ_CLIENT_SECRET = os.environ.get('QQ_CLIENT_SECRET', '')

WEIBO_CLIENT_ID = os.environ.get('WEIBO_CLIENT_ID', '')
WEIBO_CLIENT_SECRET = os.environ.get('WEIBO_CLIENT_SECRET', '')

GITHUB_CLIENT_ID = os.environ.get('GITHUB_CLIENT_ID', '')
GITHUB_CLIENT_SECRET = os.environ.get('GITHUB_CLIENT_SECRET', '')

GITEE_CLIENT_ID = os.environ.get('GITEE_CLIENT_ID', '')
GITEE_CLIENT_SECRET = os.environ.get('GITEE_CLIENT_SECRET', '')

# 回调地址
VITE_REDIRECT_URI = 'https://{}/callback/'.format(os.environ.get('HOST_URL', ''))

